<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;

class AuthController extends Controller
{
    use ThrottlesLogins;

    //登录
    public function login(Request $request)
    {
        if($request->userName && $request->password){
             //验证登录次数
            if($this->hasTooManyLoginAttempts($request))
            {
                $this->fireLockoutEvent($request);

                return $this->sendLockoutResponse($request);
            }
            $credentials = [
                'name' => $request->userName,
                'password' => $request->password,
            ];
            if(!Auth::attempt($credentials)){
                $this->incrementLoginAttempts($request);
                return $this->error('账号和密码错误');
            }
            $user = $request->user();

            $tokenResult = $user->createToken('apis');
            $token = $tokenResult->token;

            $token->expires_at = Carbon::now()->addWeeks(1);

            $token->save();

            return $this->success([
                'access_token' => $tokenResult->accessToken,
                'token_type' => 'Bearer',
                'expires_at' => Carbon::parse(
                    $tokenResult->token->expires_at
                )->toDateTimeString()
            ]);
        }
        return $this->error('账号密码不能为空');
    }


    //退出
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();

        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }

    //管理员信息
    public function userinfo()
    {
        $users =  Auth::user();
        $roles = $users->getRoleNames();
        // $perms = $users->getAllPermissions();
        // if($users->is_admin())
        // {
        //     $perms->push(['name' => 'super_admin']);
        // }
        return $this->success(['users'=>$users, 'roles' => $roles]);
    }

    //我的未读
    public function messageCount()
    {
       return Auth::user()->unreadNotifications()->count();
    }

    //我的消息列表
    public function messageList()
    {
        $user   = Auth::user();
        $unread = $user->unreadNotifications()->get()->map(function($item){
            $data = [
                'title'       => $item->data['title'],
                'msg_id'      => $item->id,
                'create_time' => $item->created_at->toDateTimeString(),
            ];
            return $data;
        });

        $readed = $user->notifications()->whereNotNull('read_at')->get()->map(function($item){
            $data = [
                'title'       => $item->data['title'],
                'msg_id'      => $item->id,
                'loading'     => false,
                'create_time' => $item->created_at->toDateTimeString(),
            ];
            return $data;
        });

        // $trash = $user->notifications()->whereNotNull('deleted_at')->get()->map(function($item){
        //     $data = [
        //         'title'       => $item->data['title'],
        //         'msg_id'      => $item->id,
        //         'loading'     => false,
        //         'create_time' => $item->created_at->toDateTimeString(),
        //     ];
        //     return $data;
        // });

        return [
            'unread' =>  $unread,
            'readed' =>  $readed,
            // 'trash'  =>  $trash,
        ];
    }

    public function messageContent()
    {
        $content = Auth::user()->notifications()->where('id',request()->msg_id)->first();

        switch ($content->data['type']) {
            case 'export':
                $path = config('app.url').$content->data['path'];
                return "<a href='{$path }' target='_blank' download='{$path}'>点击下载表格：{$path }</a>";
                break;

            default:
                return '暂无消息';
                break;
        }
    }
    //已读消息
    public function hasRead()
    {
        return Auth::user()->notifications()->where('id',request()->msg_id)->update(['read_at'=>now()]);
    }

    //软删除
    public function removeReaded()
    {
        return Auth::user()->notifications()->where('id',request()->msg_id)->delete();
    }

    //还原消息
    public function restore()
    {
        return Auth::user()->notifications()->where('id',request()->msg_id)->update(['deleted_at'=>null]);
    }

    public function username()
    {
        return 'name';
    }

    protected function sendLockoutResponse(Request $request)
    {
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );
        return $this->error(Lang::get('auth.throttle', ['seconds' => $seconds]),422);
    }

    public function notice()
    {
        $time = time();
        $user   = Auth::user();
        $notice = $user->notifications()->get()->map(function($item){
            $noticeTime = strtotime($item->created_at->toDateTimeString());
            $data = [
                'title'       => $item->data['title'],
                'create_time' => strtotime($item->created_at->toDateTimeString()),
            ];
            return $data;
        });
        $notice = $notice->toArray();
        $res = [];
        foreach ($notice as $k => $v){
            if($v['create_time'] + 5 > $time){
                $res[] = $v;
            }
        }

        return $this->success($res);
    }
}
